<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="800px"
    title="新建配送服务"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-form-item
        label="配送商名称"
        prop="distributeName"
      >
        <div class="label">{{ formData.distributeName }}</div>

      </el-form-item>
      <el-form-item
        v-if="dialogType==='edit'"
        label="配送服务编号"
        prop="distributeServeNo"
      >
        <div class="label">{{ formData.distributeServeNo }}</div>

      </el-form-item>
      <el-form-item
        label="配送产品"
        prop="distributeName"
      >
        <template v-if="dialogType==='create'">
          <el-row>
            <div style="width: 540px;">
              <el-select
                v-model="currentSelect"
                style="width: 540px;"
                filterable
                placeholder="请选择"
                @change="selectChange"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.productPopularName"
                  :value="item"
                />
              </el-select>
            </div>
            <div style="width: 98px;text-align: center;">
              <el-button
                type="text"
                style="font-size:14px"
                @click="addProduct"
              >添加</el-button>
            </div>
          </el-row>
          <div
            v-if="selectData.length"
            class="select-list"
            style="margin-top: 10px;"
          >
            <el-table
              :data="selectData"
              size="small"
              header-cell-class-name="table-header"
              border
            >
              <el-table-column
                prop="productPopularName"
                label="配送产品"
                width="540px"
              />
              <el-table-column
                label="操作"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    type="text"
                    @click="cancelProduct(scope.$index)"
                  >取消</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
        <template v-else>
          <div>
            {{ formData.productPopularName }}- {{ formData.packSpecs }}/{{ formData.sellUnit }} - {{ formData.approvalNumber }}
          </div>
        </template>
      </el-form-item>
      <el-form-item
        label="配送地区"
        prop="area"
      >
        <el-cascader
          ref="cascader"
          v-model="formData.area"
          :popper-append-to-body="false"
          style="width: 100%;"
          :options="citys"
          placeholder="请选择配送地区"
          :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
          collapse-tags
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item
        label="配送费"
        prop="expireTime"
      >
        <el-row style="margin-bottom: 20px">
          <el-col :span="6">
            <el-radio
              v-model="formData.computeMode"
              label="固定价格"
              value="固定价格"
            >固定价格</el-radio>
          </el-col>
          <el-col :span="18">
            <el-input
              v-model="formData.distributePrice"
              placeholder="请输入配送费"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
              @blur="()=>formData.distributePrice = Number(formData.distributePrice)"
            >
              <template #append><span>元</span><span> / 计价单位</span></template>
            </el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-radio
              v-model="formData.computeMode"
              label="终端价百分百"
              value="终端价百分百"
            >按终端价百分百</el-radio>
          </el-col>
          <el-col :span="18">
            <el-input
              v-model="formData.distributePrice"
              placeholder="请输入配送费"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
              @blur="()=>formData.distributePrice = Number(formData.distributePrice)"
            >
              <template #append><span>%</span></template>
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="关联合同"
        prop="contractId"
      >
        <el-select
          v-model="formData.contractId"
          style="width: 100%"
          filterable
          placeholder="请选择合同"
        >
          <el-option
            v-for="item in contractOptions"
            :key="item.id"
            :label="item.contractName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="服务结束日期"
        prop="expireTime"
      >
        <el-date-picker
          v-model="formData.expireTime"
          style="width: 100%"
          type="date"
          placeholder="选择服务结束日期"
        />
      </el-form-item>
      <el-form-item label="配送时效约定">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入下架原因"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="submit"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import area from '@/utils/area.js'

export default defineComponent({
  name: 'CreateService',
  emits: ['onsuccess'],
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const citys = area
    const formRef = ref(null)
    const cascader = ref(null)
    var reactiveData = reactive({
      dialogType: 'create',
      distributorDetail: null,
      productOptions: [{ id: 18, productPopularName: '阿莫西林' }],
      contractOptions: [{ id: 1, contractName: '关联配送合同' }],
      contractForm: {
        objectId: 0,
        contractObjectType: 'delivery',
        contractType: 'distribute_contrart',
        keyWord: '',
      },
      currentSelect: null,
      selectData: [],
      formData: {
        distributeId: 0,
        contractId: 0,
        productIds: [],
        region: [],
        expireTime: '',
        distributePrice: 0,
        computeMode: '固定价格',
        remark: '',
      },
    })
    var formRules = reactive({
      distributeName: [
        { required: true, message: '请选择配送产品', trigger: 'change' },
      ],
      area: [
        {
          required: true,
          message: '请选择适用地区',
          trigger: 'change',
        },
      ],
      expireTime: [
        {
          required: true,
          message: '请选择服务结束日期',
          trigger: 'change',
        },
      ],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = async(type, detail) => {
      reactiveData.dialogType = type
      reactiveData.distributorDetail = detail.distributorDetail
      reactiveData.contractForm.objectId = detail.distributorDetail.id
      reactiveData.formData.distributeId = detail.distributorDetail.id
      reactiveData.formData.distributeName =
        detail.distributorDetail.distributeName

      if (reactiveData.dialogType === 'edit') {
        var disService = await api.distributors.DISTRIBUTORS_SERVICE_DETAIL({
          id: detail.distributorDetail.id,
        })
        if (disService.code === 0) {
          reactiveData.formData = {
            ...disService.data.DistributeServe,
            area: currentInstance.proxy.getCascaderAreaData(
              disService.data.DistributeServe.region
            ),
          }
        }
      }

      // 获取有效合同列表
      getValidContract()

      dialogShow.value = true
    }
    const getValidContract = () => {
      api.common.VALID_CONTRACT_LIST(reactiveData.contractForm).then((res) => {
        if (res.code === 0) {
          reactiveData.contractOptions = res.data
        }
      })
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const selectChange = (val) => {
      console.log(val)
      reactiveData.currentSelect = val
    }
    const cancelProduct = (index) => {
      reactiveData.selectData.splice(index, 1)
    }
    const addProduct = () => {
      if (reactiveData.currentSelect) {
        var isExit = reactiveData.selectData.findIndex(
          (p) => p.id === reactiveData.currentSelect.id
        )
        if (isExit < 0) {
          reactiveData.selectData.unshift(reactiveData.currentSelect)
        }
      }
    }
    const areaChange = (val) => {
      reactiveData.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
    }
    const createOperation = () => {
      reactiveData.formData.productIds = reactiveData.selectData.map((p) => {
        return p.id
      })
      console.log(reactiveData.formData)
      api.distributors
        .DISTRIBUTORS_SERVICE_CREATE(reactiveData.formData)
        .then((res) => {
          if (res.code === 0) {
            console.log('创建成功')
            close()
          }
        })
    }
    const submit = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (reactiveData.dialogType === 'create') {
            createOperation()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      citys,
      formRef,
      cascader,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      submit,
      addProduct,
      selectChange,
      cancelProduct,
      areaChange,
    }
  },
})
</script>
